import api from '@/pages/Shop/ClassifyManagement/request';
import { PlusOutlined } from '@ant-design/icons';
import { DrawerForm, ProFormSlider, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Form } from 'antd';
import { useMemo, useState } from 'react';

export type Data = ShopClassifyManagementApi.InfoResponse;
export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  isEdit?: boolean;
  data?: Data;
  onSuccess?: () => void;
  onCancel?: () => void;
}
const colSpan = 2;
function ShopClassifyManagementForm(props: Props) {
  const { data, isEdit = false } = props;
  const [form] = Form.useForm<Data>();
  const [info, setInfo] = useState<Partial<ShopClassifyManagementApi.InfoResponse>>({});

  const onSubmit = async (form: Data) => {
    const { classifyName, orderNo } = form;
    const { id = '' } = info;
    if (isEdit) {
      const params: ShopClassifyManagementApi.UpdateParams = {
        id,
        classifyName,
        orderNo,
      };
      const data = await api.update(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    } else {
      const params: ShopClassifyManagementApi.CreateParams = {
        classifyName,
        orderNo,
      };
      const data = await api.create(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    }
  };
  const onOpenChange = (open: boolean) => {
    if (open) {
      if (data) {
        const info = isEdit ? data : {};
        setInfo(info);
        form.setFieldsValue(info);
      }
    } else {
      setInfo({});
      form.resetFields();
      props.onCancel?.();
    }
  };

  const formConfig = useMemo(() => {
    const classifyName = {
      Component: ProFormText,
      props: {
        name: 'classifyName',
        rules: [{ required: true }],
        width: 'md',
        label: '门店分类',
        placeholder: '请输入门店分类',
      },
    };
    const orderNo = {
      Component: ProFormSlider,
      props: {
        name: 'orderNo',
        width: 'md',
        label: '排序',
        placeholder: '请输入排序',
        min: 1,
        max: 100,
      },
    };
    const createForm: {
      [key in string]: FormConfig;
    } = { classifyName, orderNo };
    const updateForm: {
      [key in string]: FormConfig;
    } = { classifyName, orderNo };
    return isEdit ? updateForm : createForm;
  }, [isEdit]);
  const drawerFormData = useMemo(() => {
    const data: FormConfig[][] = [];
    const keys = Object.keys(formConfig);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      const index = Math.floor(i / colSpan);
      if (!data[index]) data[index] = [];
      data[index].push(formConfig[key]);
    }
    return data;
  }, [formConfig]);

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`${isEdit ? '编辑' : '新建'}分类`}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
        onResize() {},
      }}
      trigger={
        isEdit ? (
          <Button type="link">编辑</Button>
        ) : !!data ? (
          <Button type="link">新建</Button>
        ) : (
          <Button type="primary">
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>
        )
      }
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      {drawerFormData.map((item) => {
        return item.map((data) => {
          const { props, Component } = data;
          return <Component key={props.name} {...props} />;
        });
      })}
    </DrawerForm>
  );
}

export default ShopClassifyManagementForm;
